package com.example.test.db;



import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DBOpenHelper extends SQLiteOpenHelper {
    /**
     * 声明一个AndroidSDK自带的数据库变量db
     */
    private SQLiteDatabase db;
    public DBOpenHelper(Context context){
        super(context,"db_test",null,1);
        db = getReadableDatabase();
    }
    public void onCreate(SQLiteDatabase db){
        db.execSQL("CREATE TABLE IF NOT EXISTS user(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT," +
                "password TEXT)"
        );
    }
    //版本适应
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }

    public void register(String name, String password){
        db.execSQL("INSERT INTO user (name,password) VALUES(?,?)",new String[]{name,password});
    }

    public boolean login(String name,String password){
        @SuppressLint("Recycle") Cursor cursor = db.query("user",null,"name = ?",new String[]{name},null,null,null);
        if (cursor.moveToFirst()){
            String nameC = cursor.getString(1);
            String passwordC = cursor.getString(2);
            if (name.equals(nameC) && password.equals(passwordC)){
                return true;
            }else {
                return false;
            }
        }
        return false;
    }
//    public void update(String password){
//        db.execSQL("UPDATE user SET password = ? AND name",new String[]{password});
//    }


    ArrayList<User> getAllData(){
        ArrayList<User> list = new ArrayList<>();
        @SuppressLint("Recycle") Cursor cursor = db.query("user",null,null,null,null,null,null);
        while(cursor.moveToNext()){
            String name = cursor.getString(1);
            String password = cursor.getString(2);

            list.add(new User(name,password));
        }
        return list;
    }
}

